import sys
import mdp
import loadData
import matplotlib.pyplot as mpl


def main(filename):
    # load data from file
    try:
        mats = loadData.load(filename)
        trainingMat = mats[0]
        testingMat = mats[1]
        print('Data loaded')
    except Exception as e:
        print(e)
        exit(1)
    
    # perform PCA on training data
    pcaNode = mdp.nodes.PCANode(svd=True)
    pcaResult = pcaNode.execute(trainingMat)
    if pcaResult is not None:
        print('PCA performed successfully')
        print 'PCA Explained Variance: ', pcaNode.explained_variance
        avg = pcaNode.avg # mean of the input data
        v = pcaNode.get_projmatrix() # projection matrix
    else:
        print('PCA failed')

    # perform LLE on training data using 15 nearest neighbors, output dim of 2
    lleNode = mdp.nodes.LLENode(15, output_dim=2)
    lleResult = lleNode.execute(trainingMat)
    if lleResult is not None:
        print('LLE performed successfully')
    else:
        'LLE failed'

    # plot PCA results (first two eigenvectors)
    mpl.figure('PCA')
    mpl.plot(pcaResult[0,:], pcaResult[1,:], 'ro')
    mpl.xlabel('row 0')
    mpl.ylabel('row 1')
    # plot LLE results
    mpl.figure('LLE')
    mpl.plot(lleResult[:,0], lleResult[:,1], 'ro')
    mpl.xlabel('column 0')
    mpl.ylabel('column 1')

    # display both figures
    mpl.show()
    
    

# display the proper command usage and exit
def commandFormat():
    print('python analyze.py <path_to_data>')
    exit(1)


if __name__=='__main__':
    # check for valid arguments
    if len(sys.argv)<2:
        commandFormat()
    # run analysis on given file
    main(sys.argv[1])
